package com.hzt.system.controller;

import com.hzt.system.common.Constant;
import com.hzt.system.common.DataGridView;
import com.hzt.system.common.ResultObj;
import com.hzt.system.domain.Menu;
import com.hzt.system.service.MenuService;
import com.hzt.system.vo.MenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
*
*
* @Author:hzt
* @Date:8:54 下午 2020/7/15
*/
@RestController
@RequestMapping("api/menu")
public class MenuController {
    @Autowired
    private MenuService menuService;

    @RequestMapping("loadAllMenu")
    public Object loadAllMenu(MenuVo menuVo){
        return menuService.loadAllMenu(menuVo);
    }


    //查询最大排序码
    @GetMapping("queryMenuMaxOrderNum")
    public Object queryMenuMaxOrderNum(){
        Integer  maxValue=this.menuService.queryMenuMaxOrderNum();
        return new DataGridView(maxValue+1);
    }


    /**
     * 要放入缓存的
     *  @param menu
     * @return
     */
    @PostMapping("addMenu")
    public ResultObj addMenu(Menu menu){
        try {
            if(menu.getType().equals("topmenu")){
                menu.setPid(0);
            }
            menu.setAvailable(Constant.AVAILABLE_TRUE);
            menu.setSpread(Constant.SPREAD_FALSE);
            this.menuService.saveMenu(menu);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    //更新操作
    @RequestMapping("updateMenu")
    public ResultObj updateMenu(Menu menu){
        try {
            this.menuService.updateMenu(menu);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    //根据id找对象，主要获取部门title
    @GetMapping("getMenuById")
    @ResponseBody
    public Object getMenuById(Integer id){
        Menu byId = menuService.getById(id);
        System.out.println(byId);
        return new DataGridView(this.menuService.getById(id));
    }


    //查找当前部门下有无子节点
    @GetMapping("getMenuChildCountById")
    public Object getMenuChildCountById(Integer id){
       Integer count= this.menuService.queryMenuChildCountById(id);
        return new DataGridView(count);
    }


    //删除
    @RequestMapping("deleteMenu")
    public ResultObj deleteMenu(Menu menu){
        try {
            this.menuService.removeById(menu.getId());
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }



    /**
     * 查询菜单
     * @param menuVo
     * @return
     */
    @RequestMapping("loadMenu")
    public Object loadMenu(MenuVo menuVo){
        List<Menu> menus = this.menuService.queryAllMenuForList();
        return new DataGridView(Long.valueOf(menus.size()),menus);
     }

}
